package com.lk.springboot.controller;

import com.lk.springboot.bean.Massage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 图片上传
 */
@Controller
public class PicUploadController {

    @RequestMapping("/picUpload")
    public String picUpload() {
        return "picUpload";
    }

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object upload(MultipartFile fileUpload, HttpServletRequest req) {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID() + suffixName;
        //按照日期，动态指定文件夹存储图片
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String filePath = "/bookstoreimgs/" + sdf.format(new Date());
        String imgFolderPath = req.getServletContext().getRealPath(filePath);
        //创建文件目录
        File folder = new File(imgFolderPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        try {
            //将图片保存到imgs文件夹里
            fileUpload.transferTo(new File(folder, fileName));
            return new Massage(0, "success to upload");
        } catch (Exception e) {
            e.printStackTrace();
            return new Massage(-1, "fail to upload");
        }
    }
}